<template>
	<view class="content page-bg" id="guide-container">
		<mask-guide-uni ref="maskGuide">
			<button slot='nextButton' class="guide-next" style="">我知道啦~</button>
		</mask-guide-uni>

		<!--  #ifdef  MP-WEIXIN -->
		<div class="title" :style="{'paddingTop': statusBarHeight + 'px','height':menuBarHeight + 'px'}">
			<!-- #endif -->
			<!--  #ifdef  MP-TOUTIAO -->
			<div class="title">
				<!-- #endif -->
				<image src="../../static/more.svg" class="logo" mode="" @click="jumpMe" id="guide_0"
					data-guide-text="点击去我的中心"></image>
				<text class="brand"></text>
			</div>

			<div class="user-avatar-box" id="guide_1" data-guide-text="点击修改我的头像">
				<button class="user-avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
					<image :src="userInfo.avatar" class="user-avatar" mode="scaleToFill"></image>
					<img src="../../static/camera.svg" class="camera-icon" alt="" srcset="">
				</button>

			</div>
			<div class="user-name-box " id="guide_2" data-guide-text="点击修改我的昵称">
				<!-- <u--input v-model="userInfo.nickname" placeholder="请输入昵称" class="user-name-input"></u--input>  :value="nickName"-->
				<input type="nickname" placeholder="请输入昵称" v-model="nickName" @input="onNameChange"
					class="user-name-input" />
			</div>

			<div class="user-tips-box">
				<text>建议修改为微信头像昵称</text>
			</div>

			<button class="btn-primary" @click="joinRoomCheckClick(currentRoom.inviteCode)"
				v-if="currentRoom.id">回到{{currentRoom.roomName}}</button>
			<button class="btn-primary" @click="joinRoomClick(shareRoom.inviteCode)"
				v-else-if="(!currentRoom.id)&& shareRoom.id">加入{{shareRoom.roomName}}</button>
			<view class="btn-create-box" v-else>
				<button class="btn-primary btn-create" @click="createRoomClick" id="guide_3"
					data-guide-text="点击创建房间">创建房间</button>
				<view class="" @click.stop="showMorePopup" id="guide_4" data-guide-text="点击扫一扫加入房间">
					<img src="../../static/more_circle.svg" class="btn-more-icon" alt="" srcset="">
				</view>

			</view>

			<div class="guide-btn-box" @click="showGuideMask">使用说明</div>
			<div class="app-info">
				<view class="logo-con">
					<image src="../../static/logo.svg" class="app-logo" mode=""></image>
					<text>记分工具人</text>
				</view>

				<text class="app-tips">本程序仅供娱乐，请勿用于非法活动</text>
				<text class="app-tips">远离赌博，快乐生活</text>
			</div>
			<IndexMorePopup ref="indexMorePopup"></IndexMorePopup>
	</view>
</template>

<script>
	import {
		updateAvatar,
		updateNickname,
		updateCid
	} from '../../api/user'

	import {
		createRoom,
		checkRoom,
		joinPartnerRoom,
		joinObserverRoom,
		getLeaderRoom
	} from '../../api/room'
	import IndexMorePopup from "../../components/IndexMorePopup.vue"
	import maskGuideUni from "../../components/mask-guide-uni/mask-guide-uni.vue"
	const app = getApp();

	export default {
		components: {
			IndexMorePopup,
			maskGuideUni
		},
		data() {
			return {
				menuBarHeight: app.globalData.menuBarHeight,
				statusBarHeight: app.globalData.statusBarHeight,
				avatarUrl: "",
				nickName: "",
				currentRoom: {
					id: undefined
				},
				shareRoom: {
					id: undefined
				},
				routeCode: undefined, //normal 正常加载 share 分享进来的
				guideKey: 'indexGuide'
			}
		},
		computed: {
			userInfo() {
				return this.$store.getters.userInfo
			},

		},
		onLoad(query) {
			this.routeCode = query.scene
			this.nickName = this.userInfo.nickname
			this.updateCid();
			//如果分享进来的，需要再checkInRoom里判断是否还在房间里，如果还在其他房间里，需要退出去才可以
			if (this.routeCode === 'share') {
				this.shareRoom = uni.getStorageSync("share")
			}

			var that = this
			uni.$on("exitRoom", this.onExitRoom)
			// if (!uni.getStorageSync(this.guideKey)) {
			// 	this.showGuideMask()
			// 	uni.setStorageSync(this.guideKey, true)
			// }

			this.showTrialVipModal()
		},
		onShow() {
			this.checkInRoom();
		},
		onUnload() {
			uni.$off("exitRoom")
		},
		methods: {
			showTrialVipModal() {
				if (!uni.getStorageSync("TrialVip")) {
					uni.showModal({
						showCancel: false,
						content: "测试期间成功创建房间并邀请同伴加入，即可自动领取30天VIP"
					})
					uni.setStorageSync("TrialVip", true)
				}

			},
			showGuideMask() {
				this.$refs.maskGuide.start({
					textStyle: {
						fontSize: '24upx',
					},
					showNextButton: true
				})
			},
			showMorePopup() {
				this.$refs.indexMorePopup.open()
			},
			onExitRoom() {
				//为啥直接赋值对象undefined时不会触发更新呢
				this.currentRoom = {
					id: undefined
				}
				this.shareRoom = {
					id: undefined
				}
			},
			checkInRoom() {
				checkRoom().then(result => {
					console.log("checkInRoom", result)
					if (result.data) {
						//还有房间没有退出
						this.currentRoom = result.data
						if (this.routeCode === 'share') {
							//如果分享进来的，要提示一下有房间没有退出，需要判断一下是否是一个房间
							if (this.shareRoom.id === this.currentRoom.id) {
								//如果绑定关系为参与者 不动
								//如果是绑定关系为观察着 覆盖掉
								if (this.currentRoom.bindType === 2) {
									//如果是参与者
									this.currentRoom.id = undefined
								}

							} else {
								uni.showModal({
									showCancel: false,
									content: "您已经加入了其他房间，请先回到房间退出"
								})
							}
						}

					}
				})
			},
			updateCid() {
				uni.getPushClientId({
					success: (res) => {
						console.log('getPushClientId', res.cid);
						updateCid({
							cid: res.cid
						}).then(result => {

						})
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			jumpMe() {
				uni.navigateTo({
					url: "/pages/me/me"
				})
			},
			//正常途径加入，需要判断自己在房间里的类型
			joinRoomCheckClick(inviteCode) {
				if (this.currentRoom.bindType === 1) {
					//参与者
					this.joinRoomClick(inviteCode)
				} else if (this.currentRoom.bindType === 2) {
					//观察员
					var that = this
					uni.getPushClientId({
						success: (res) => {
							console.log('getPushClientId', res.cid);
							joinObserverRoom({
								cid: res.cid,
								code: that.currentRoom.observerCode,
								source: "mp"
							}).then(result => {
								uni.setStorageSync("o_room", result.data)
								uni.navigateTo({
									url: "/pages/observerRoom/observerRoom"
								})
							}).catch(err => {
								that.checkInRoom()
							})
						},
						fail(err) {
							console.log(err)
						}
					})

				}
			},
			joinRoomClick(inviteCode) {
				if (!this.nickName) {
					uni.$u.toast('请输入昵称')
					return;
				}
				if (this.nickName !== this.userInfo.nickname) {
					updateNickname({
						nickname: this.nickName
					}).then(res => {
						this.userInfo.nickname = this.nickName
						this.$store.commit('SET_USER_INFO', this.userInfo)
						this.joinRoom(inviteCode)
					})
				} else {
					this.joinRoom(inviteCode)
				}

			},
			joinRoom(code) {
				joinPartnerRoom({
					inviteCode: code
				}).then(result => {
					uni.setStorageSync("room", result.data)
					uni.navigateTo({
						url: "/pages/room/room"
					})
				}).catch(err => {
					that.checkInRoom()
				})
			},
			createRoomClick() {
				if (!this.nickName) {
					uni.$u.toast('请输入昵称')
					return;
				}
				if (this.nickName !== this.userInfo.nickname) {
					updateNickname({
						nickname: this.nickName
					}).then(res => {
						this.userInfo.nickname = this.nickName
						this.$store.commit('SET_USER_INFO', this.userInfo)
						this.createRoom()
					})
				} else {
					this.createRoom()
				}


			},
			createRoom() {
				var that = this
				createRoom({
					roomName: this.userInfo.nickname + "的房间",
					type: 1
				}).then(result => {
					uni.setStorageSync("room", result.data)
					uni.navigateTo({
						url: "/pages/room/room"
					})
				}).catch(err => {
					console.log("createRoom err", err)
					if (err.data) {
						if (err.data.code === 1050001006) {
							//已经创建过房间了 显示房间重新加入
							getLeaderRoom().then(result => {
								if (result.data) {
									uni.showModal({
										content: "之前创建的房间还没有解散，是否去解散房间",
										confirmText: "确定",
										success: function(res) {
											if (res.confirm) {
												that.joinRoom(result.data.inviteCode)
											} else if (res.cancel) {
												console.log('用户点击取消');
											}
										}
									})
								}
							})
						}
					}
				})

			},
			onNameChange(e) {
				// console.log("e.target.value", e.target.value)
				// this.nickName = e.target.value
			},
			onChooseavatar(e) {
				let self = this;
				let {
					avatarUrl
				} = e.detail;
				uni.showLoading({
					title: '加载中'
				});
				updateAvatar(avatarUrl).then(res => {
					this.userInfo.avatar = res.data
					this.$store.commit('SET_USER_INFO', this.userInfo)
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
				})




				// uni.uploadFile({
				// 	url: '后台uploadFile接口',
				// 	filePath: avatarUrl,
				// 	name: 'file',
				// 	header: {
				// 		token: '自己的token',
				// 	},
				// 	success: uploadFileRes => {
				// 		// 注意：这里返回的uploadFileRes.data 为JSON 需要自己去转换
				// 		let data = JSON.parse(uploadFileRes.data);
				// 		if (data.code === 0) {
				// 			this.avatarUrl = data.data;
				// 		}
				// 	},
				// 	fail: (error) => {
				// 		uni.showToast({
				// 			title: error,
				// 			duration: 2000
				// 		});
				// 	},
				// 	complete: () => {
				// 		uni.hideLoading();
				// 	}
				// });
			},

		}
	}
</script>

<style scoped lang="scss">
	.content::before {
		content: "";
		clear: both;
		display: table;
	}

	.content {
		// background: linear-gradient(180deg, $uni-color-primary, #f2f7ff10);
		position: relative;
		height: 100vh;
		width: 100vw;

		.guide-next {
			background-color: transparent;
			width: 100%;
			height: 50upx;
			font-size: 20upx;
			color: white;
		}

		.guide-next::after {
			border-color: white;
		}

		.title {
			width: 100%;
			display: flex;
			align-items: center;

			.logo {
				width: 60upx;
				height: 60upx;
				margin-left: 40upx;
			}

			.brand {
				font-size: 40upx;
				color: black;
				margin-left: 20upx;
				font-weight: bolder;
			}
		}


		.user-avatar-box {
			height: auto;
			margin: 20% auto 0;
			width: 100%;
			display: flex;
			justify-content: center;

			.user-avatar-btn {
				border: none;
				background-color: transparent;
				display: block;
				position: relative;
				padding-top: 10upx;
				padding-bottom: 10upx;
			}

			button::after {
				border: none;
			}

			.user-avatar-btn ::after {
				border: 0px solid transparent !important;
			}

			.user-avatar {
				background-color: #fff;
				border-radius: 100%;
				box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .4);
				height: 200upx;
				overflow: hidden;

				width: 200upx;
				border: 8upx solid #fff;
				position: relative;

			}

			.camera-icon {
				width: 50upx;
				height: 50upx;
				position: absolute;
				bottom: 40upx;
				right: 40upx;
				border-radius: 25upx;
				border: 4upx solid #fff;
				background-color: #fff;
			}
		}

		.user-name-box {
			height: 100upx;

			margin: 0 64upx;
			margin-top: 64upx;

			.user-name-input {
				background-color: #fff;
				border-radius: 12upx;
				box-shadow: 0 5upx 10upx 0 rgba(0, 0, 0, .05);
				font-size: 40upx;
				font-weight: 600;
				height: 100upx;
				line-height: 100upx;
				text-align: center;
				width: 100%;
			}
		}

		.user-tips-box {
			color: #00000050;
			font-size: 26upx;
			margin-top: 48upx;
			text-align: center
		}

		.btn-primary {
			border-radius: 16upx !important;
			font-size: 36upx !important;
			// height: 100upx !important;
			line-height: 100upx !important;
			margin: 0 40upx;
			background-color: $uni-color-primary;
			color: white;
			font-weight: 200;
			margin-top: 200upx;
		}

		.btn-create-box {
			display: flex;

			align-items: center;
			margin-left: 40upx;
			margin-top: 200upx;
		}

		.btn-create {
			margin-top: 0upx !important;
			flex-grow: 1;
			margin: 0 !important;
		}

		.btn-more-icon {
			height: 60upx;
			width: 30upx;
			flex-shrink: 0;
			margin-left: 24upx;
			margin-right: 40upx;
			cursor: pointer;
		}

		.guide-btn-box {
			border-bottom-color: #c8c8cf;
			color: #c8c8cf
		}

		.guide-btn-box {

			border-bottom: 2upx solid #000;
			color: #2f2f2f;
			font-size: 28upx;
			font-weight: 500;
			margin: 56upx auto auto;
			width: -webkit-fit-content;
			width: fit-content
		}

		.app-info {
			bottom: 64upx;
			position: absolute;
			text-align: center;
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;


			.logo-con {
				display: flex;
				align-items: center;
				color: #2f2f2f;
				font-size: 28upx;
				margin-bottom: 20upx;
			}

			.app-logo {
				height: 60upx;
				width: 60upx;
				margin-right: 12upx;

			}

			.app-tips {
				color: #00000050;
				font-size: 24upx;

			}
		}
	}
</style>